<?php

require_once( "MDB2.php" );
require_once( "db/DatabaseException.php" );

abstract class AbstractDatabaseObject extends Object {
	protected $dsn;
	protected $db;
	
	public function __construct( $dsn ) {
		if ( !$dsn )
			throw new DatabaseException();
		
		$this->dsn = $dsn;
		$this->db = MDB2::factory( $dsn );
		
		if (MDB2::isError( $this->db ) ) {
			throw new DatabaseException( $this->db->getUserInfo() );
		}
	}
	
	private function checkError( $db_result ) {
		if (MDB2::isError( $db_result )) {
			$description  = 'Standard Message: ' . $db_result->getMessage() . "<BR>";
			$description .= 'Standard Code: ' . $db_result->getCode() . "<BR>";
			$description .= 'MDB2/User Message: ' . $db_result->getUserInfo() . "<BR>";
			$description .= 'MDB2/Debug Message: ' . $db_result->getDebugInfo() . "<BR><BR>";			
			echo $description;
			return false;
		}
		else
			return true;
	}
	
	
	protected function prepareStatement( $sql ) {
		print_r($sql);
		$statement = $this->db->prepare( $sql );
		if ( !$this->checkError( $statement ) )
			throw new DatabaseException("Initial prepared mappers statements invalid<BR> <pre>$sql</pre>");
		return $statement;
	}
		
	protected function doQuery( $sql ) {
		$db_result = $this->db->query( $sql );
		
		if ( !$this->checkError( $db_result ) )
			return false;
		
		return $db_result;
	}
	
	protected function doExecute($statement, $values) {	
		if ( !$this->checkError( $statement ) )
			return false;
			
		$db_result = $statement->execute($values);
		
		if ( !$this->checkError( $db_result ) )
			return false;
		
		return $db_result;
	}
		
	protected function getNextId() {
		return $this->db->nextId( $this->getTableName() );
	}
	
	abstract public function getTableName();
	
	
}



?>